/*
 * Copyright (C) The Apache Software Foundation. All rights reserved.
 *
 * This software is published under the terms of the Apache Software License
 * version 1.1, a copy of which has been included with this distribution in
 * the LICENSE file.
 */
package ranab.server.ftp.gui;

import java.awt.Font;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.Properties;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;

import ranab.gui.GuiUtils;
import ranab.gui.PropertiesTableModel;
import ranab.server.ServerEngine;
import ranab.server.ftp.FtpConfig;
import ranab.server.ftp.FtpServer;


/**
 * FTP user interface root panel. We can start, stop
 * the server using this panel.
 *
 * @author <a href="mailto:rana_b@yahoo.com">Rana Bhattacharyya</a>.
 */
public 
class FtpRootPanel extends JPanel {
    
    private final static String START_IMG = "ranab/server/ftp/gui/start.gif";
    private final static String STOP_IMG = "ranab/server/ftp/gui/stop.gif";
    private final static String BROWSE_IMG = "ranab/server/ftp/gui/browse.gif";
    
    private final static Properties EMPTY_PROP = new Properties();
    
    private JButton mjBrowseBtn = null;
    private JButton mjStartBtn  = null;
    private JButton mjStopBtn   = null;
    private JTextField mjCfgTxt = null;
    private JTable mjCfgTbl     = null;
    
    private FtpTree mTree              = null;    
    private File mCfgFile              = null;
    private ServerEngine mServerEngine = null;  
    
    private boolean mbServerRunning = false;
    
    /** 
     * Creates new panel for root. 
     */
    public FtpRootPanel(FtpTree tree) {
        mTree = tree;
        initComponents ();
    }
    
    /** 
     * This method is called from within the constructor to
     * initialize the form.
     */
    private void initComponents() {
        
        setLayout(new BorderLayout());
        
        // top panel
        JPanel topPane = new JPanel();
        topPane.setLayout(new GridBagLayout());
        GridBagConstraints gc = new GridBagConstraints();
        gc.insets = new Insets(0, 0, 0, 10);
        
        JLabel cfgLab = new JLabel("Configuration File");
        cfgLab.setForeground(Color.black);
        cfgLab.setFont(new Font(null, Font.BOLD, 12));
        gc.gridx = 0;
        gc.gridy = 0;
        gc.gridwidth = 4;
        topPane.add(cfgLab, gc);
        
        mjCfgTxt = new JTextField();
        mjCfgTxt.setColumns(20);
        gc.gridx = 0;
        gc.gridy = 1;
        gc.gridwidth = 3;
        topPane.add(mjCfgTxt, gc);
        mjCfgTxt.setText("../apps/ftp/conf/ftpd.conf");
        
        //mjBrowseBtn = new JButton("Browse", GuiUtils.createImageIcon(BROWSE_IMG));
        mjBrowseBtn = new JButton("Browse");
        gc.gridx = 3;
        gc.gridy = 1;
        gc.gridwidth = 1;
        topPane.add(mjBrowseBtn, gc);
        
        JPanel btnPane = new JPanel();
        btnPane.setLayout(new FlowLayout(FlowLayout.CENTER));
        
        mjStartBtn = new JButton("Start", GuiUtils.createImageIcon(START_IMG));
        btnPane.add(mjStartBtn);
        
        mjStopBtn = new JButton("Stop", GuiUtils.createImageIcon(STOP_IMG));
        mjStopBtn.setEnabled(false);
        btnPane.add(mjStopBtn);
        
        gc.gridx = 0;
        gc.gridy = 2;
        gc.gridwidth = 4;
        topPane.add(btnPane, gc);
        
        add(topPane, BorderLayout.NORTH);
        
        
        // bottom panel - display config parameters
        PropertiesTableModel cfgModel = new PropertiesTableModel(EMPTY_PROP);
        mjCfgTbl = new JTable(cfgModel);
        mjCfgTbl.setPreferredScrollableViewportSize(new Dimension(470, 260));
        mjCfgTbl.setColumnSelectionAllowed(false);
        JScrollPane bottomPane = new JScrollPane(mjCfgTbl, 
                                    JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                                    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        add(bottomPane, BorderLayout.CENTER);
        
        // event handlers
        mjBrowseBtn.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent evt) {
               browseConfig();
           }
        });
        
        mjStartBtn.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent evt) {
               startServer();
           }
        });

        mjStopBtn.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent evt) {
               stopServer();
           }
        });
    }
    
    /**
     * Browse configuration file.
     */
    public void browseConfig() {
        String cfgFile = GuiUtils.getFileName(mTree.getTopFrame());
        if(cfgFile != null) {
           mjCfgTxt.setText(cfgFile); 
        }
    }
     
    /**
     * Start the ftp server.
     */
    public void startServer() {
      
      String fileName = mjCfgTxt.getText().trim();  
      if(fileName.equals("")) {
          GuiUtils.showErrorMessage(mTree.getTopFrame(), "Please select a config file.");
          return;
      } 
      
      // start server
      if(mServerEngine != null) {
          mServerEngine.stopServer();
      }
      try {
          mCfgFile = new File(fileName);
          FtpServer server = new FtpServer(mCfgFile);
          mServerEngine = new ServerEngine(server);
          mServerEngine.startServer();
      }
      catch(Throwable ex) {
         if(ex instanceof InvocationTargetException) {
            ex = ((InvocationTargetException)ex).getTargetException();
         }
        
         GuiUtils.showErrorMessage(mTree.getTopFrame(), ex.getClass().getName() + " : " + ex.getMessage());
         ex.printStackTrace();
         mServerEngine = null;
         return;
      }
      
      mbServerRunning = true;
      FtpServer ftpServer = (FtpServer)mServerEngine.getServer();
      FtpConfig config = ftpServer.getConfig();
      ((PropertiesTableModel)mjCfgTbl.getModel()).reload(config);
      
      mjStartBtn.setEnabled(false);
      mjCfgTxt.setEnabled(false);
      mjBrowseBtn.setEnabled(false);
      mjStopBtn.setEnabled(true);
      mTree.refresh(config);
    }
    
    
    /**
     * Stop FTP server.
     */
    public void stopServer() {
      
      // get confirmation
      boolean conf = GuiUtils.getConfirmation(mTree.getTopFrame(), "Do you really want to stop?"); 
      if(!conf) {
        return;
      }
          
      if(mServerEngine != null) {
          mServerEngine.stopServer();
          mServerEngine = null;
      }  
      mbServerRunning = false;
      ((PropertiesTableModel)mjCfgTbl.getModel()).reload(EMPTY_PROP);
      mjStartBtn.setEnabled(true);
      mjCfgTxt.setEnabled(true);
      mjBrowseBtn.setEnabled(true);
      mjStopBtn.setEnabled(false);
      mTree.refresh(null);
    }
    
    /**
     * Get FTP server.
     */
    public ServerEngine getServerEngine() {
        return mServerEngine;
    }
   
}
